package controller

import (
    . "api/model"
    . "api/service"
	"net/http"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"path"
    "strconv"
)

func ImportExcel(c *gin.Context) {
    customerMap, err := GetCustomerMap()
    if err != nil {
        c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        return
    }

    promotionOfficerMap, err := GetPromotionOfficerMap()
    if err != nil {
        c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        return
    }

    securitiesCompanyMap, err := GetSecuritiesCompanyMap()
    if err != nil {
        c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        return
    }

    creditCardMap, err := GetCreditCardMap()
    if err != nil {
        c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        return
    }

    customerRecordMap, err := GetCustomerRecordMap()
    if err != nil {
        c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        return
    }

	file, err := c.FormFile("file")
	if err != nil {
        c.JSON(http.StatusOK, gin.H{"error": "上传文件出错"})
        return
	}

	dst := path.Join("./upload", file.Filename)

    c.SaveUploadedFile(file, dst)

	f, err := excelize.OpenFile(dst)

	defer func() {
        if err := f.Close(); err != nil {
            c.JSON(http.StatusOK, gin.H{"error": err.Error()})
            return
        }
    }()

    rows, err := f.GetRows("Sheet1")
    if err != nil {
        c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        return
    }

    associateIds := map[int]int{}
    newOrders := []*Order{}

    if len(rows) <= 1 {
        c.JSON(http.StatusOK, gin.H{"error": "Excel无数据"})
        return
    }

    if len(rows[0]) != 6 {
        c.JSON(http.StatusOK, gin.H{"error": "Excel列数错误"})
        return
    }

    for i := 0; i < len(rows); i++ {
        if i != 0 {
            phone := rows[i][0]

            if len(phone) != 11 {
                c.JSON(http.StatusOK, gin.H{"error": "手机号码必须为11位数字"})
                return
            }

            tradingAt := rows[i][1]

            status, err := strconv.Atoi(rows[i][2])
            if err != nil {
                c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                return
            }

            if status != 0 && status != 1 {
                c.JSON(http.StatusOK, gin.H{"error": "订单状态只能为数字0或数字1"})
                return
            }

            pType, err := strconv.Atoi(rows[i][4])
            if err != nil {
                c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                return
            }

            if pType != 1 && pType != 2 {
                c.JSON(http.StatusOK, gin.H{"error": "产品类型只能为数字1或数字2"})
                return
            }

            pId, err := strconv.Atoi(rows[i][3])
            if err != nil {
                c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                return
            }

            pName := rows[i][5]
            times := 0

            for k, v := range customerMap {
                if phone[0:3] == v.Phone[0:3] && phone[7:11] == v.Phone[7:11] {
                    times ++
                    var moneyTotal, moneyToSelf, moneyToMaster int

                    if pType == 1 {
                        if _, ok := securitiesCompanyMap[pId]; ok {
                            moneyTotal = securitiesCompanyMap[pId].TotalPromotionFee
                            moneyToSelf = securitiesCompanyMap[pId].PromotionOfficerAward
                            moneyToMaster = securitiesCompanyMap[pId].ApprenticeAward
                        } else {
                            c.JSON(http.StatusOK, gin.H{"error": "Excel中产品类型或产品ID有误，Error -> securitiesCompanyMap"})
                            return
                        }
                    }

                    if pType == 2 {
                        if _, ok := creditCardMap[pId]; ok {
                            moneyTotal = creditCardMap[pId].TotalPromotionFee
                            moneyToSelf = creditCardMap[pId].PromotionOfficerAward
                            moneyToMaster = creditCardMap[pId].ApprenticeAward
                        } else {
                            c.JSON(http.StatusOK, gin.H{"error": "Excel中产品类型或产品ID有误，Error -> creditCardMap"})
                            return
                        }
                    }

                    cid := k
                    var crid int

                    if status == 1 {
                        // 核心查找
                        for k2, v2 := range customerRecordMap {
                            if cid == v2.CustomerId && pType == v2.ProductType && pId == v2.ProductId {
                                crid = k2
                            }
                        }

                        if crid == 0 {
                            c.JSON(http.StatusOK, gin.H{"error": "Excel中存在异常数据"})
                            return
                        }

                        // 结算给推广官
                        promotionOfficerMap, associateIds, err = Settle(crid, moneyToSelf, moneyToMaster, promotionOfficerMap, customerMap, customerRecordMap, associateIds)
                        if err != nil {
                            c.JSON(http.StatusOK, gin.H{"error": err.Error()})
                            return
                        }
                    }

                    // 订单数据map
                    newOrders = StructOrder(newOrders, crid, phone, tradingAt, status, pId, pType, pName, moneyTotal, moneyToSelf, moneyToMaster, promotionOfficerMap, customerMap, customerRecordMap)
                }
            }

            if times == 0 {
                c.JSON(http.StatusOK, gin.H{"error": "没有查询到脱敏号码 " + phone + " 的消费记录"})
                return
            }

            if times >= 2 {
                c.JSON(http.StatusOK, gin.H{"error": "脱敏号码查到" + strconv.Itoa(times) + "个用户号码"})
                return
            }
        }
    }

    associateInfoMap := map[int]*PromotionOfficer{}

    for k, _ := range associateIds {
        associateInfoMap[k] = promotionOfficerMap[k]
    }

    err = ValidatedDatabase(promotionOfficerMap)
    if err != nil {
        c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        return
    }

    // 同步推广官表和订单表
    p := PromotionOfficer{}
    err = p.SynPromotionOfficerAndOrder(associateInfoMap, newOrders)
    if err != nil {
        c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        return
    }

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success"})
}